package com.redribbon.droidnoise;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class ClientController extends Activity {

	StreamClientService clientService = null;
	
	private boolean isStreaming;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isStreaming = false;
     
        setContentView(R.layout.client_2);
        startClient();
        setupGUI();
	}
		
	@Override
	protected void onRestoreInstanceState(Bundle savedInstaceState) {
		super.onRestoreInstanceState(savedInstaceState);
		isStreaming = savedInstaceState.getBoolean("isStreaming");
		startClient();
	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putBoolean("isStreaming", isStreaming);
	}
	
	private void setupGUI() {
		final Button s2_back_button = (Button) findViewById(R.id.client_2_stop_button);
        s2_back_button.setOnClickListener(mStopListener);
	}
	
	private void startClient() {
		if (!isStreaming) {
            // Make sure the service is started.  It will continue running
            // until someone calls stopService().
			//TODO pass data
			startService(new Intent(ClientController.this, StreamClient.class));
		}
	}
	
    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            // Cancel a previous call to startService().  Note that the
            // service will not actually stop at this point if there are
            // still bound clients.
            stopService(new Intent(ClientController.this, StreamClient.class));
            finish();
        }
    };
    
    public void showMetadata(String station, String track, String artist, String album) {
    	((TextView)findViewById(R.id.client_2_station_name)).setText(station);
    	((TextView)findViewById(R.id.client_2_song_name)).setText(track);
    	((TextView)findViewById(R.id.client_2_artist)).setText(artist);
    	((TextView)findViewById(R.id.client_2_album)).setText(track);
    }
    
    /**
    * Class for interacting with the main interface of the service.
    */
   private ServiceConnection mConnection = new ServiceConnection() {
       public void onServiceConnected(ComponentName className,
               IBinder service) {
           // This is called when the connection with the service has been
           // established, giving us the service object we can use to
           // interact with the service.  We are communicating with our
           // service through an IDL interface, so get a client-side
           // representation of that from the raw service object.
           clientService = StreamClientService.Stub.asInterface(service);

           // We want to monitor the service for as long as we are
           // connected to it.
           try {
               clientService.registerCallback(mCallback);
           } catch (RemoteException e) {
               // In this case the service has crashed before we could even
               // do anything with it; we can count on soon being
               // disconnected (and then reconnected if it can be restarted)
               // so there is no need to do anything here.
           }
       }

       public void onServiceDisconnected(ComponentName className) {
           // This is called when the connection with the service has been
           // unexpectedly disconnected -- that is, its process crashed.
           clientService = null;
       }
   };

   /**
    * This implementation is used to receive callbacks from the remote
    * service.
    */
   private StreamClientServiceCallback mCallback = new StreamClientServiceCallback.Stub() {
       /**
        * This is called by the remote service regularly to tell us about
        * new values.  Note that IPC calls are dispatched through a thread
        * pool running in each process, so the code executing here will
        * NOT be running in our main thread like most other things -- so,
        * to update the UI, we need to use a Handler to hop over there.
        */
       public void valueChanged(int value) {
           mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
       }
   };
   
   private static final int BUMP_MSG = 1;
   
   private Handler mHandler = new Handler() {
       public void handleMessage(Message msg) {
           switch (msg.what) {
               case BUMP_MSG:
                   //Update metadata
            	   showMetadata(NoiseConstants.current_playing_station, NoiseConstants.current_playing_track, NoiseConstants.current_playing_artist, NoiseConstants.current_playing_album);
                   break;
               default:
                   super.handleMessage(msg);
           }
       }

   };
}
